package com.woyao;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.ContactSummary;
import com.woyao.core.model.UserSummary;
import com.woyao.core.service.ChanceService;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;

import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class InviteActivity extends AppCompatActivity {
    ProgressDialog progressDialog;
    private ContactAdapter contactAdapter;
    private RecyclerView contactList = null;
    LinearLayoutManager contactLayoutManager = null;
    Button clickInvite;
    ArrayList<ContactSummary> contacts = new ArrayList<ContactSummary>() ;

    private TextView  relationCount;

    private ContentResolver cr;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite);

        Toolbar toolbar = (Toolbar) findViewById(R.id.invite_toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        contactLayoutManager = new LinearLayoutManager(this);
        contactLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        contactList = (RecyclerView)findViewById(R.id.invite_list);
        contactList.setLayoutManager(contactLayoutManager);
        contactList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));



        this.setTitle("邀请朋友们");

        relationCount  = (TextView) findViewById(R.id.myrelation_count);

        clickInvite  = (Button) findViewById(R.id.invite_click);
        clickInvite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                invite( contactAdapter.getSelection(),true);
            }
        });

        Button clearBtn  = (Button) findViewById(R.id.id_clearall);
        clearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                renderThem(false);
//                invite( contactAdapter.getSelection(),false);
            }
        });

        Button selectAllBtn  = (Button) findViewById(R.id.id_selectall);
        selectAllBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                renderThem(true);
//                invite( contactAdapter.getSelection(),false);
            }
        });
        tryGetContacts();
    }



    public  void tryGetContacts() {

        if (ContextCompat.checkSelfPermission(InviteActivity.this,android.Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions( InviteActivity.this,
                    new String[]{android.Manifest.permission.READ_CONTACTS},
                    1);
            Log.i("woyaooo","'授权了吗？'");
        }else{
            getContacts();
        }




    }

    private void getContacts() {

        ArrayList<String> dups = new ArrayList<String>();
        try {

            cr = getContentResolver();
//            Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            Cursor cs = null;

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                cs = cr.query(uri, null, null, null,  "sort_key", null);
                StringBuilder sb = new StringBuilder();
                while (cs.moveToNext()) {
                    try {
                        //拿到联系人id 跟name
                        int id = cs.getInt(cs.getColumnIndex("_id"));

                        String number = cs.getString(cs.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        number = number.replace(" ","").replace("+86","");

                        if (dups.contains( number ) ){
                            continue;
                        }
                        dups.add(number);
                        String name = cs.getString(cs.getColumnIndex("display_name"));



                        ContactSummary one = new ContactSummary();
                        one.setId(number);
                        one.setTitle(name  );
                        one.setDescription(number);
                        if (!one.getId().equals("") && !one.getTitle().equals("") && one.getId().length() == 11 && one.getId().startsWith("1") ){
                            contacts.add( one);
                        }

                        sb.append("displayname:" + name + ";");
                        sb.append("phone:" + number + ";");
                        sb.append("#");

                    }catch (Exception e){
                        Log.i("woyaooo", e.getMessage());
                    }
                }
                renderThem(true);
//                saveReload( sb.toString()) ;
//                Common.setProfileAttr("contacts", sb.toString());

            }

        }catch (Exception e){
            Toast.makeText(this,"不能访问通讯录", Toast.LENGTH_SHORT).show();
        }
    }


//    public   void saveReload( final String content){
//        progressDialog = new ProgressDialog(InviteActivity.this);
//        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        progressDialog.setMessage("正在获取数据······");
//        progressDialog.show();
//        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
//            @Override
//            protected Boolean doInBackground(Void... params) {
//                AccountService svc = ServiceFactory.get(AccountService.class);
//                Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,"contacts",content);
//                Boolean ret = true ;
//                try {
//                    BaseResponse response = responseCall.execute().body();
//                    ret= response.isSuccess();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    ret = false;
//                }
//                return ret;
//            }
//
//            @Override
//            protected void onPostExecute(final Boolean success) {
//                progressDialog.dismiss();
//                if (success) {
//                    loadUser("unregistered");
//                } else {
//
//                }
//            }
//
//            @Override
//            protected void onCancelled() {
//                progressDialog.dismiss();
//            }
//        };
//        task.execute((Void) null);
//
//    }
//
//    public void loadUser( final String kw){
//
//
//
//
//        AsyncTask<Void,Void, GetMyUserResponse> task1 =new AsyncTask<Void, Void, GetMyUserResponse>() {
//            @Override
//            protected GetMyUserResponse doInBackground(Void... params) {
//                AccountService svc = ServiceFactory.get(AccountService.class);
//                Call<GetMyUserResponse> responseCall = svc.getMyUser(userId,kw);
//                try {
//                    GetMyUserResponse response = responseCall.execute().body();
//                    return response;
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                return null;
//            }
//            @Override
//            protected void onPostExecute(final GetMyUserResponse response) {
//                current = response;
//                renderThem(response,true);
//
//            }
//            @Override
//            protected void onCancelled() {
//
//            }
//        };
//        task1.execute((Void)null);
//    }


//
//    public  void tryGetContacts() {
//
//        if (ContextCompat.checkSelfPermission(InviteActivity.this,android.Manifest.permission.READ_CONTACTS)
//                != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions( InviteActivity.this,
//                    new String[]{android.Manifest.permission.READ_CONTACTS},
//                    1);
//            Log.i("woyaooo","'授权了吗？'");
//        }else{
//            getContacts();
//        }
//
//
//
//
//    }
//
//    private void getContacts() {
//        ArrayList<ContactSummary> contacts = new ArrayList<ContactSummary>();
//        ArrayList<String> dups = new ArrayList<String>();
//        try {
//
//            cr = getContentResolver();
////            Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
//            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
//            Cursor cs = null;
//
//            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
//                cs = cr.query(uri, null, null, null,  "sort_key", null);
//                StringBuilder sb = new StringBuilder();
//                while (cs.moveToNext()) {
//                    try {
//                        //拿到联系人id 跟name
//                        int id = cs.getInt(cs.getColumnIndex("_id"));
//
//                        String number = cs.getString(cs.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//                        number = number.replace(" ","").replace("+86","");
//
//                        if (dups.contains( number ) ){
//                            continue;
//                        }
//                        dups.add(number);
//                        String name = cs.getString(cs.getColumnIndex("display_name"));
//
//
//
//                        ContactSummary one = new ContactSummary();
//                        one.setId(number);
//                        one.setTitle(name  );
//                        one.setDescription(number);
//                        if (!one.getId().equals("") && !one.getTitle().equals("") && one.getId().length() == 11 && one.getId().startsWith("1") ){
//                            contacts.add( one);
//                        }
//
//                        sb.append("displayname:" + name + ";");
//                        sb.append("phone:" + number + ";");
//                        sb.append("#");
//
//                    }catch (Exception e){
//                        Log.i("woyaooo", e.getMessage());
//                    }
//                }
//                renderThem(contacts);
//                Common.setProfileAttr("contacts", sb.toString());
//
//            }
//
//        }catch (Exception e){
//            Toast.makeText(this,"不能访问通讯录", Toast.LENGTH_SHORT).show();
//        }
//    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {    // 1 for location
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.i("woyaooo","'已经授权'");
                    getContacts();

                } else {
                    Log.i("woyaooo","'没有授权'");
                    finish();
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }


    private  void renderThem(  Boolean selected){

//        if (!response.getMessage().equals("")) {
//            Toast.makeText(InviteActivity.this, response.getMessage(), Toast.LENGTH_LONG).show();
////            Common.alert(InviteActivity.this,response.getMessage());
////            Dialog alertDialog = new android.support.v7.app.AlertDialog.Builder(InviteActivity.this).
////                    setTitle("信息").
////                    setMessage(response.getMessage()).
////                    setIcon(R.drawable.ic_launcher).
////                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
////
////                        @Override
////                        public void onClick(DialogInterface dialog, int which) {
////
////                        }
////                    }).
////                    create();
////            alertDialog.show();
//        }

        for  ( ContactSummary us : contacts){
            us.setSelected(selected);
        }
        if (selected) {
            clickInvite.setText("一键短信邀请" + contacts.size() + "人");
        }else{
            clickInvite.setText("一键短信邀请");
        }
        contactAdapter = new ContactAdapter(this,  contacts );

        relationCount.setText( contacts.size() +"位联系人");

        contactList.setAdapter(contactAdapter);
        contactAdapter.setChangedHandler(new ContactAdapter.Changed() {
                                             @Override
                                             public void view(UserSummary cs) {
                                                 invite(cs.getTitle() + "#" + cs.getMobile(), false);
                                             }

                                             @Override
                                             public void selectionChanged(Integer num) {
                                                 clickInvite.setText("一键短信邀请" + num +"人");
                                             }
                                         });


    }


    private void invite( final String  mobiles, final Boolean done) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在处理···");
        progressDialog.show();

        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<BaseResponse> responseCall = svc.invite(userId, mobiles);
                try {
                    BaseResponse r = responseCall.execute().body();
                    return r;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(final BaseResponse ret) {
                progressDialog.dismiss();
                if (ret != null) {
                    if (ret.isSuccess()) {
//                        Toast.makeText(InviteActivity.this, "成功处理!", Toast.LENGTH_SHORT).show();
                        if (done){
//                                                    Toast.makeText(InviteActivity.this, "成功处理!", Toast.LENGTH_SHORT).show();
                        Dialog alertDialog = new AlertDialog.Builder(InviteActivity.this).
                                setTitle("信息").
                                setMessage("已经完成!").
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                    }
                                }).
                                create();
                        alertDialog.show();


                        }


                    }else{
                        Toast.makeText(InviteActivity.this, "处理失败!", Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void) null);
    }


}
